package com.xuerhua.yxt.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.DictDataCode;
import com.xuerhua.yxt.common.enums.GuideStatus;
import com.xuerhua.yxt.common.enums.NoticeType;
import com.xuerhua.yxt.common.enums.RelationType;
import com.xuerhua.yxt.common.enums.SendeeType;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.common.enums.UserRole;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.NoticeRecord;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.NoticeQueryVO;
import com.xuerhua.yxt.reqVo.NoticeReqVO;
import com.xuerhua.yxt.service.INoticeSendeeService;
import com.xuerhua.yxt.service.INoticeService;
import com.xuerhua.yxt.service.ISchoolWechatTemplateService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.BeanUtils;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.view.NoticeRecordView;
import com.xuerhua.yxt.view.TeacherInfoView;

/**
 * 通知控制器
 * @author huqimeng
 * @date 2017年5月21日
 */
@Controller
public class NoticeController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(NoticeController.class);
	
	@Autowired
	private INoticeService noticeService;
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private INoticeSendeeService noticeSendeeService;
	@Autowired
	private ISchoolWechatTemplateService schoolWechatTemplateService;

	/**
	 * 班级通知发布页
	 * @param model
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.NOTICE_CLASS)
	public String noticeClass(Model model){
		AppUser appUser = getAppUser();
		if(appUser.getTeacher().getClazz() == null) {
			BaseQueryVO vo = new BaseQueryVO();
			vo.setFinishYear(getCurrentTerm().getFinishYear());
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setId(appUser.getTeacher().getId());
			List<TeacherInfoView> teacherInfoView = teacherService.selectClassForTeacher(vo);
			if(!StringUtil.isNullOrEmpty(teacherInfoView)) {
				appUser.getTeacher().setClazz(teacherInfoView.get(0).getClazz());
				appUser.getTeacher().setGrade(teacherInfoView.get(0).getGrade());
			}
		}
		model.addAttribute("noticeType", NoticeType.NOTICE_CLASS.getCode());
		model.addAttribute("relationType", RelationType.NOTICE.getCode());
		return "notice/classPublish";
	}
	
	/**
	 * 文件传阅发布页
	 * @param model
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.NOTICE_FILEAROUND)
	public String noticeFilearound(Model model){
		AppUser appUser = getAppUser();
		model.addAttribute("noticeType", NoticeType.NOTICE_FILEAROUND.getCode());
		model.addAttribute("relationType", RelationType.NOTICE.getCode());
		if(StringUtil.isExist(appUser.getTeacher().getPosition(), "5002")) {
			return "notice/fileAround";
		}
		model.addAttribute("isPrincipal", StringUtil.isExist(appUser.getTeacher().getPosition(), "1001"));
		return "notice/fileAroundList";
	}
	
	/**
	 * 行政通知发布页
	 * @param model
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.NOTICE_EXECUTIVE)
	public String noticeExecutive(Model model){
		model.addAttribute("noticeType", NoticeType.NOTICE_EXECUTIVE.getCode());
		model.addAttribute("relationType", RelationType.NOTICE.getCode());
		return "notice/executivePublish";
	}
	
	/**
	 * 科级通知发布页
	 * @param model
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.NOTICE_SUBJECT_GRADE)
	public String noticeSubjectGrade(Model model){
		model.addAttribute("noticeType", NoticeType.NOTICE_SUBJECT_GRADE.getCode());
		model.addAttribute("relationType", RelationType.NOTICE.getCode());
		return "notice/teacherPublish";
	}
	
	/**
	 * 作业通知发布页
	 * @param model
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.NOTICE_HOMEWORK)
	public String noticeHomework(Model model) {
		model.addAttribute("noticeType", NoticeType.NOTICE_HOMEWORK.getCode());
		model.addAttribute("relationType", RelationType.NOTICE.getCode());
		return "notice/homework";
	}
	
	/**
	 * 通知创建接口
	 * @param reqVO
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + "/notice/create")
	@ResponseBody Object noticeCreate(NoticeReqVO reqVO){
		try {
			AppUser appUser = getAppUser();
			NoticeRecord record = BeanUtils.copyAs(reqVO, NoticeRecord.class);
			record.setSchoolId(appUser.getTeacher().getSchoolId());
			record.setSchoolName(appUser.getTeacher().getSchoolName());
			record.setTermId(getCurrentTerm().getId());
			if(reqVO.getNoticeType() == NoticeType.NOTICE_CLASS.getCode()) {
				reqVO.setSendModel(SendeeType.PARENT.getCode());
				String templateId = schoolWechatTemplateService.selectTemplateKey(
						record.getSchoolId(), DictDataCode.CLASS_NOTICE.getCode());
				record.setTemplateCode(templateId);
			}else if(reqVO.getNoticeType() == NoticeType.NOTICE_HOMEWORK.getCode()) {
				reqVO.setSendModel(SendeeType.PARENT.getCode());
				String templateId = schoolWechatTemplateService.selectTemplateKey(
						record.getSchoolId(), DictDataCode.HOMEWORK_NOTICE.getCode());
				record.setTemplateCode(templateId);
			}else {
				String templateId = schoolWechatTemplateService.selectTemplateKey(
						record.getSchoolId(), DictDataCode.SCHOOL_NOTICE.getCode());
				record.setTemplateCode(templateId);
			}
			reqVO.setSubject(appUser.getTeacher().getSubjectText());
			record.setSenderId(appUser.getTeacher().getId());
			record.setSender(appUser.getTeacher().getName());
			record.setSendeeType(reqVO.getSendModel());
			if(reqVO.getNoticeType() == NoticeType.NOTICE_FILEAROUND.getCode()) {
				record.setGuideStatus(GuideStatus.PENDING.getCode());
			}
			noticeService.createNotice(reqVO, record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---noticeCreate error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notice/repeat")
	@ResponseBody Object noticeRepeat(Integer noticeId) {
		try {
			NoticeReqVO reqVO = new NoticeReqVO();
			AppUser appUser = getAppUser();
			NoticeRecord record = noticeService.selectByPrimaryKey(noticeId);
			reqVO.setNoticeType(record.getNoticeType());
			reqVO.setSendModel(record.getSendeeType());
			reqVO.setSubject(appUser.getTeacher().getSubjectText());
			reqVO.setRepeat(true);
			noticeService.repeatNotice(reqVO, record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---noticeRepeat error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	/**
	 * 今日已发布通知接口
	 * @param vo
	 * @return
	 */
	@RequestMapping(Const.TEACHER_ROLE + "/notices/sender/today")
	@ResponseBody Object todayNotice(NoticeQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSenderId(appUser.getTeacher().getId());
		vo.setStartDate(DateUtil.dateToStr(new Date(), DateUtil.DATE_FORMAT1));
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		return noticeService.selectListByParam(vo);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notices/sender/list")
	public String noticeSenderList(Model model) {
		AppUser appUser = getAppUser();
		model.addAttribute("noticeType", request.getParameter("nt"));	//作业通知
		model.addAttribute("senderId", appUser.getTeacher().getId());
		return "notice/noticeList";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notices/list")
	public String noticeSendeeList(Model model) {
		AppUser appUser = getAppUser();
		model.addAttribute("noticeType", request.getParameter("nt"));
		model.addAttribute("sendeeId", appUser.getTeacher().getId());
		model.addAttribute("sendeeOpenid", appUser.getTeacher().getOpenid());
		return "notice/noticeList";
	}
	
	@RequestMapping(Const.STUDENT_ROLE + "/notices/list")
	public String studentNoticeList(Model model) {
		AppUser appUser = getAppUser();
		model.addAttribute("noticeType", request.getParameter("nt"));
		model.addAttribute("sendeeOpenid", appUser.getParent().getOpenid());
		return "notice/noticeList";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notices/detail/{noticeId}")
	public String noticeDetail(@PathVariable Integer noticeId, Model model) {
		Integer sendeeId = getAppUser().getTeacher().getId();
		Integer schoolId = getAppUser().getTeacher().getSchoolId();
		NoticeQueryVO queryVO = new NoticeQueryVO();
		queryVO.setNoticeId(noticeId);
		queryVO.setSendeeId(sendeeId);
		queryVO.setSchoolId(schoolId);
		NoticeRecordView notice = noticeService.selectViewByNoticeId(queryVO);
		model.addAttribute("notice", notice);
		model.addAttribute("sendeeId", sendeeId);
		return "notice/noticeDetail";
	}
	
	@RequestMapping(Const.STUDENT_ROLE + "/notices/detail/{noticeId}")
	public String noticeDetail1(@PathVariable Integer noticeId, Model model) {
		String sid = request.getParameter("sid");
		Integer studentId = StringUtils.isNotBlank(sid) ? Integer.valueOf(sid) : null;
		Integer sendeeId = getAppUser().getParent().getId();
		NoticeQueryVO queryVO = new NoticeQueryVO();
		queryVO.setSendeeId(sendeeId);
		queryVO.setNoticeId(noticeId);
		queryVO.setStudentId(studentId);
		queryVO.setSchoolId(getAppUser().getParent().getSchoolId());
		NoticeRecordView notice = noticeService.selectViewByNoticeId(queryVO);
		model.addAttribute("notice", notice);
		model.addAttribute("sendeeId", sendeeId);
		return "notice/noticeDetail";
	}
	
	@RequestMapping("notice/read/modify")
	@ResponseBody Object noticeRead(Integer sendeeId, @RequestParam("noticeIds[]")List<Integer> noticeIds) {
		try {
			noticeSendeeService.updateRead(sendeeId, noticeIds);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----noticeRead error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("notice/read/list")
	@ResponseBody Object noticeReadList(Integer noticeId, Integer sendeeType) {
		if(sendeeType == SendeeType.PARENT.getCode()) {
			return noticeSendeeService.selectListForParentByNoticeId(noticeId);
		}
		return noticeSendeeService.selectListByNoticeId(noticeId);
	}
	
	@RequestMapping("notice/page/query")
	@ResponseBody Object noticePageQuery(NoticeQueryVO vo) {
		try {
			Page<NoticeRecord> page = new Page<NoticeRecord>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			Integer schoolId = getAppUser().getRoleType()==UserRole.TEACHER.getCode() ? getAppUser().getTeacher().getSchoolId() : getAppUser().getParent().getSchoolId();
			vo.setSchoolId(schoolId);
			sorts.add(new OrderBy("CREATE_TIME", "desc"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<NoticeRecord> list = noticeService.selectListByPage(page);
			List<NoticeRecordView> listView = BeanUtils.copyAs(list, NoticeRecordView.class);
			grid.setRows(listView);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("---noticePageQuery error={}", e);
		}
		return null;
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notice/fileAround/detail/{noticeId}")
	public String fileAroundDetail(@PathVariable Integer noticeId, Model model) {
		String share = request.getParameter("share");
		if(StringUtils.isNotBlank(share) && share.equals(RelationType.FILE_AROUND.getCode())) {
			NoticeQueryVO queryVO = new NoticeQueryVO();
			queryVO.setNoticeId(Integer.valueOf(noticeId));
			queryVO.setSendeeId(0);
			queryVO.setSchoolId(getAppUser().getTeacher().getSchoolId());
			NoticeRecordView notice = noticeService.selectViewByNoticeId(queryVO);
			model.addAttribute("notice", notice);
			return "share/fileAroundShare";
		}
		AppUser appUser = getAppUser();
		Integer sendeeId = getAppUser().getTeacher().getId();
		NoticeQueryVO queryVO = new NoticeQueryVO();
		queryVO.setNoticeId(noticeId);
		queryVO.setSendeeId(sendeeId);
		queryVO.setSchoolId(getAppUser().getTeacher().getSchoolId());
		NoticeRecordView notice = noticeService.selectViewByNoticeId(queryVO);
		model.addAttribute("notice", notice);
		model.addAttribute("sendeeId", sendeeId);
		model.addAttribute("isPrincipal", StringUtil.isExist(appUser.getTeacher().getPosition(), "1001"));
		return "notice/fileAroundDetail";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notice/fileAround/end")
	@ResponseBody Object fileAroundPrincipalEnd(NoticeReqVO vo) {
		try {
			AppUser appUser = getAppUser();
			if(!StringUtil.isExist(appUser.getTeacher().getPosition(), "1001")) {
				return new RspResult(Status.NO_POWER);
			}
			NoticeRecord record = noticeService.selectByPrimaryKey(vo.getNoticeId());
			record.setGuideContent(vo.getGuideContent());
			record.setGuideId(appUser.getTeacher().getId());
			record.setGuider(appUser.getTeacher().getName());
			record.setUpdateTime(new Date());
			record.setGuideStatus(GuideStatus.NO_SEND.getCode());
			noticeService.updateByPrimaryKeySelective(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---fileAroundPrincipalEnd error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notice/fileAround/send")
	@ResponseBody Object fileAroundPrincipalSend(NoticeReqVO vo) {
		try {
			AppUser appUser = getAppUser();
			if(!StringUtil.isExist(appUser.getTeacher().getPosition(), "1001")) {
				return new RspResult(Status.NO_POWER);
			}
			NoticeRecord record = noticeService.selectByPrimaryKey(vo.getNoticeId());
			record.setGuideContent(vo.getGuideContent());
			record.setGuideId(appUser.getTeacher().getId());
			record.setGuider(appUser.getTeacher().getName());
			record.setUpdateTime(new Date());
			record.setGuideStatus(GuideStatus.SENDED.getCode());
			record.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setSendModel(record.getSendeeType());
			noticeService.updatePrincipalSend(vo, record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---fileAroundPrincipalSend error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + "/notice/fileAround/page/query")
	@ResponseBody Object noticeFileAroundPageQuery(NoticeQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setNoticeType(NoticeType.NOTICE_FILEAROUND.getCode());
			vo.setSendeeId(appUser.getTeacher().getId());
			Page<NoticeRecord> page = new Page<NoticeRecord>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			if(vo.getType() == 0) {
				sorts.add(new OrderBy("CREATE_TIME", "desc"));
			}else {
				sorts.add(new OrderBy("UPDATE_TIME", "desc"));
			}
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<NoticeRecord> list = null;
			if(StringUtil.isExist(appUser.getTeacher().getPosition(), "1001")) {
				list = noticeService.selectListForFileAroundByPage(page);
			}else {
				list = noticeService.selectListForFileAroundByPage1(page);
			}
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("---noticeFileAroundPageQuery error={}", e);
		}
		return null;
	}
	
}
